package club.ruanx.auth.token;

import club.ruanx.security.bean.UserAuthInfo;
import club.ruanx.security.bean.UserAuthInfoContextHolder;
import club.ruanx.security.property.AuthenticationTokenProperties;
import club.ruanx.security.token.UserTokenGenerator;
import club.ruanx.security.util.JwtTokenUtil;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * @author 阮胜
 * @date 2018/9/23 14:21
 */
@Component
public class JwtUserTokenGeneratorImpl implements UserTokenGenerator {
    /**
     * 用户ID
     */
    private static final String UID = "uid";
    private final AuthenticationTokenProperties authenticationTokenProperties;

    public JwtUserTokenGeneratorImpl(AuthenticationTokenProperties authenticationTokenProperties) {
        this.authenticationTokenProperties = authenticationTokenProperties;
    }

    @Override
    public String generate() throws Exception {
        UserAuthInfo userAuthInfo = UserAuthInfoContextHolder.getCurrentUserAuthInfo();
        HashMap<String, Object> map = new HashMap<>(1);
        map.put(UID, userAuthInfo.getUid());
        return authenticationTokenProperties.getPrefix().concat(JwtTokenUtil.generate(userAuthInfo.getUsername(), map, 60 * 60 * 24 * 30, authenticationTokenProperties.getSecret()));
    }
}
